from aiogram import Router, types, F
from aiogram.fsm.context import FSMContext
from django.db.models import CharField, Q
from django.db.models.functions import Cast
from loguru import logger

from database import models
from tg_bot.filters.user_filter import IsAdmin

router = Router()
router.message.filter(IsAdmin())
router.inline_query.filter(IsAdmin())
router.callback_query.filter(IsAdmin())


@router.inline_query(F.query.startswith('FIND SEAT'))
async def find_seat_inline_query(query: types.InlineQuery):
    query_data = query.query.replace('FIND SEAT ', '').lower()
    seat_list = models.Seat.objects.filter(name__icontains=query_data)
    results = []
    if seat_list.count() == 0:
        seat_list = models.Seat.objects.all()
    for seat in seat_list[:50]:
        results.append(types.InlineQueryResultArticle(
            id=f'{seat.pk}',
            title=f'{seat.name}',
            input_message_content=types.InputTextMessageContent(
                message_text=f'SEAT {seat.pk}',)
        ))

    await query.answer(results, cache_time=2)


@router.inline_query(F.query.startswith('FIND CATEGORY'))
async def find_category_inline_query(query: types.InlineQuery):
    query_data = query.query.replace('FIND CATEGORY ', '').lower()
    category_list = models.Category.objects.filter(name__icontains=query_data)
    results = []
    if category_list.count() == 0:
        category_list = models.Category.objects.all()
    for category in category_list[:50]:
        results.append(types.InlineQueryResultArticle(
            id=f'{category.pk}',
            title=f'{category.name}',
            input_message_content=types.InputTextMessageContent(
                message_text=f'CATEGORY {category.pk}',)
        ))

    await query.answer(results, cache_time=2)


@router.inline_query(F.query.startswith('FIND PRODUCT'))
async def find_product_inline_query(query: types.InlineQuery, state: FSMContext) -> None:
    """
    Инлайн поиск продукта по базе данных. В стейте должна быть категория для продукта.
    Если ее нет, то ищем все продукты.

    ----
    :param query: InlineQuery.
    :param state: FSMContext.
    :return: None
    """
    data = await state.get_data()
    category: models.Category = data.get('category')
    query_data = query.query.replace('FIND PRODUCT ', '').lower()
    product_list = models.Product.objects.filter(name__icontains=query_data)
    results = []
    if product_list.count() == 0:
        product_list = models.Product.objects.all()
    if category:
        product_list = product_list.filter(category=category)
    for product in product_list[:50]:
        results.append(types.InlineQueryResultArticle(
            id=f'{product.pk}',
            title=f'{product.name} | {product.category.name}',
            input_message_content=types.InputTextMessageContent(
                message_text=f'PRODUCT {product.pk}',)
        ))

    await query.answer(results, cache_time=2)


@router.inline_query(F.query.startswith('FIND CONSUMABLE'))
async def find_consumable_inline_query(query: types.InlineQuery):
    query_data = query.query.replace('FIND CONSUMABLE ', '').lower()
    consumable_list = models.Consumable.objects.filter(name__icontains=query_data)
    results = []
    if consumable_list.count() == 0:
        consumable_list = models.Consumable.objects.all()
    for consumable in consumable_list[:50]:
        results.append(types.InlineQueryResultArticle(
            id=f'{consumable.pk}',
            title=f'{consumable.name} | {consumable.price}x{consumable.total}{consumable.unit}',
            input_message_content=types.InputTextMessageContent(
                message_text=f'CONSUMABLE {consumable.pk}',)
        ))

    await query.answer(results, cache_time=2)


@router.inline_query(F.query.startswith('FIND USER'))
async def find_user_inline_query(query: types.InlineQuery):
    query_data = query.query.replace('FIND USER ', '').lower().split(' ')
    user_info = query_data[0]
    if len(query_data) > 1:
        try:
            discount_sum = float(query_data[-1])
        except Exception as e:
            logger.warning(e)
            discount_sum = 0.0
    else:
        discount_sum = 0.0
    user_list = models.TgUser.objects.annotate(id_as_str=Cast('user_id', CharField())).filter(
        Q(phone_number__icontains=user_info) | Q(id_as_str__icontains=user_info) | Q(name__icontains=user_info)
    )
    results = []
    if user_list.count() == 0:
        user_list = models.TgUser.objects.all()
    for user in user_list[:50]:
        if discount_sum > user.balance:
            user_discount = user.balance
        else:
            user_discount = discount_sum
        results.append(types.InlineQueryResultArticle(
            id=f'{user.pk}',
            title=f'{user.name}',
            description=f'ID: {user.user_id}, Номер: {user.phone_number}, '
                        f'Бонусы: {user.balance}, Потратить: {user_discount}',
            input_message_content=types.InputTextMessageContent(
                message_text=f'USER {user.pk} {user_discount}', )
        ))

    await query.answer(results, cache_time=2)
